import React, { useEffect, useState } from 'react'
import { Button } from 'antd'
import { MessageFilled } from '@ant-design/icons'
import style from './index.module.scss'
import computDetailRight from '@/utils/computDetailRight'
import { scrollFn } from '@/utils/utils'
export default function CommentMain() {
  const [btnClientX, setBtnClientX] = useState(0)
  const [show, setShow] = useState(true)
  const [isMonitor, setIsMonitor] = useState(false)
  const [detailDom, setDetailDom] = useState<Element | null>(null)
  const [commentTopDom, setCommentTopDom] = useState<Element | null>(null)
  const toComment = () => {
    scrollFn(
      detailDom as HTMLDivElement,
      (commentTopDom as HTMLDivElement).offsetTop + 5
    )
  }
  // 监听窗口变化 重新计算
  useEffect(() => {
    setDetailDom(document.querySelector('#detail'))
    setCommentTopDom(document.querySelector('#commentTop'))
  }, [])
  useEffect(() => {
    if (detailDom === null) return
    computDetailRight(setBtnClientX, detailDom as HTMLDivElement)
  }, [detailDom])
  // 监听detail滚动
  useEffect(() => {
    if (isMonitor || detailDom === null || commentTopDom === null) return
    setIsMonitor(true)
    detailDom?.addEventListener('scroll', () => {
      const detailScrollTop = (detailDom as HTMLElement).scrollTop
      const commentTopDomOffsetTop = (commentTopDom as HTMLElement).offsetTop
      setShow(detailScrollTop < commentTopDomOffsetTop)
    })
  }, [detailDom, commentTopDom, isMonitor])

  return (
    <>
      {show && (
        <Button
          type="primary"
          shape="circle"
          icon={<MessageFilled />}
          style={{ right: btnClientX + 'px' }}
          className={style.comment_main}
          onClick={toComment}
        />
      )}
    </>
  )
}
